package com.csun.cmny.provider.controller;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.config.RedisInitRunner;
import com.csun.cmny.provider.constant.Constant;
import com.csun.cmny.provider.model.constant.OldInConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.*;
import com.csun.cmny.provider.model.vo.GroupVo;
import com.csun.cmny.provider.model.vo.OldmanAddressVo;
import com.csun.cmny.provider.model.vo.OldmanExceptionVo;
import com.csun.cmny.provider.model.vo.ServiceOrderVO;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.pojo.OldmanFee;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.*;
import com.csun.cmny.provider.vo.*;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * 老人管理
 * */
@RestController
@RequestMapping("/Oldman")
public class OldmanController extends BaseController {

    @Resource
    private RedisInitRunner redisInitRunner;
    @Autowired
    private OldmanService oldmanService;
    @Autowired
    private OldmanFeeService oldmanFeeService;
    @Autowired
    private OldmanLeaveService oldmanLeaveService;
    @Autowired
    private BedService bedService;
    @Autowired
    private OldmanNurseHiService oldmanNurseHiService;
    @Autowired
    private OldmanCheckInService oldmanCheckInService;
    @Autowired
    private OldmanRechargeService oldmanRechargeService;
    @Resource
    private OmcOldManSupplementService oldManSupplementService;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private OmcOldManIetypeStashService omcOldManIetypeStashService;
    @Resource
    private OmcAdvisoryService omcAdvisoryService;
    @Resource
    private OmcOldManAccountFundsService accountFundsService;
    @Resource
    private OpcMessageService opcMessageService;
    @Resource
    private OmcUserTypeService userTypeService;
    @Resource
    private OmcGroupService groupService;
    @Resource
    private OmcServiceService omcServiceService;

    /*
     * 这里的认证和当前登录的用户注解先预留，等完善了再进行修改
     * 1.判断该用户是否属于该机构人员
     * */
    //添加老人
    @RequestMapping(value = "/addOldman", method = RequestMethod.POST)
    public Wrapper addOldman(@RequestBody Oldman oldman) throws ParseException {
        //校验
        if (oldman.getOldIdCard() == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人身份证号码不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.idcard.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getOldName())) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人姓名不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("advisoryCancel.oldName.null", null), null);
        }
        if (oldman.getSex() == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人性别不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("advisory.oldSex.null", null), null);
        }
        if (StringUtils.isEmpty(oldman.getBirthday())) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人出生日期不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.chushen.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getOldAddress())) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人家庭住址不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.address.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getmStatus())) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人婚姻状态不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.hunyin.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getEgNamea())) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "紧急联系人a姓名不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.urgA.name.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getEgPhonea())) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "紧急联系人a电话号码不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.urgA.phone.notnull", null), null);
        }
        if (oldman.getRelationshipa() == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "紧急联系人a与老人关系不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.urgA.relation.notnull", null), null);
        }
        if (oldman.getEgaAddress() == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "紧急联系人a家庭地址不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("OldMan.urgA.address.notnull", null), null);
        }
        //根据身份证号码判断该老人是否已经登记过
        Oldman oldman2 = new Oldman();
        oldman2.setOldIdCard(oldman.getOldIdCard());
        Oldman oldman1 = oldmanService.selectByOld(oldman2);
        if (oldman1 != null) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "该老人身份证号已存在", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("OldMan.is.exsit", null), null);
        }

        //计算老人家庭地址的百度经纬度
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getOldAddress())) {
            Map<String, Double> addressMap = BaiduMapUtils.getLngAndLat(oldman.getOldAddress());
            if (addressMap == null || addressMap.isEmpty()) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "请检查老人家庭住址是否正确", null);
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("OldMan.check.address", null), null);
            } else {
                String latitude = addressMap.get("lat").toString();
                String longitude = addressMap.get("lng").toString();
                String addressBdGps = longitude + "," + latitude;
                System.out.println("addressBdGps");
                oldman.setOldAddressBdGps(addressBdGps);
            }
        }

        //获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        oldman.setHomeId(homeId);
        //生成用户名(机构Id+随机数+系统时间的形式)
        String username = "nc_" + homeId + "_" +
                (int) (Math.random() * 100) + System.currentTimeMillis();
        oldman.setUserName(username);

        //生日  通过生日计算年龄
        String birthday = "" + oldman.getBirthday();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.parse(birthday);
        int age = 0;
        if (org.apache.commons.lang.StringUtils.isNotBlank(birthday)) {
            age = AgeUtil.getAgeFromBirthTime(birthday) - 1;
        }
        oldman.setOldAge(age);
        oldman.setOldmanNo(DateUtil.getOldmanNo());//生成老人编号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        oldman.setCreateTime(simpleDateFormat.parse(DateUtil.getCurrentDate()));
        oldman.setModifier(loginAuthDto.getUserId());
        //添加
        int n = oldmanService.insertSelective(oldman);
        if (n <= 0) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "添加失败", 0);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("comment.add.fail", null), 0);
        }
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "添加成功", oldman.getOldmanId());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("comment.add.success", null), oldman.getOldmanId());
    }

    //根据id删除老人
    @RequestMapping(value = "/delOldman", method = RequestMethod.POST)
    public Wrapper delOldman(Integer oldmanId) {
        if (oldmanId == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人id不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("oldman.id.null", null), null);
        }
        int n = oldmanService.deleteByOldId(oldmanId);

        //删除费用记录
        OldmanFee oldmanFee = oldmanFeeService.selectByOldmanId(oldmanId);
        if (oldmanFee != null) {
            oldmanFeeService.deleteByOldmanId(oldmanId);
        }

        //删除出院信息
        oldmanLeaveService.deleteByOid(oldmanId);

        //删除老人入住记录
        oldmanCheckInService.deleteByOldId(oldmanId);

        //解绑老人智能设备
        oldmanCheckInService.delOldDeviceByOid(oldmanId);

        //删除老人护理记录
        oldmanNurseHiService.deleteByOldmanId(oldmanId);

        //删除充值记录
        oldmanRechargeService.deleteByOldmanId(oldmanId);

        //删除老人绑定的个性化套餐纪录
        oldmanCheckInService.delOldItemByOid(oldmanId);

        if (n <= 0) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "没有此id", oldmanId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("oldman.not.in", null), oldmanId);
        }
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "删除成功", n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), n);
    }

    //修改老人
    @RequestMapping(value = "/updateOldman", method = RequestMethod.POST)
    public Wrapper updateCacType(Oldman oldman) throws ParseException {
        if (oldman.getOldmanId() == null) {
            //            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人id不能为空", null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("oldman.id.null", null), null);
        }
        //机构id
        Integer homeId = getLoginAuthDto().getGroupId().intValue();
        //如果修改了老人身份证，判断该身份证是否和社区的其他老人重复
        if (!StringUtils.isEmpty(oldman.getOldIdCard())) {
            Oldman oldman1 = new Oldman();
            oldman1.setOldIdCard(oldman.getOldIdCard());
            oldman1.setHomeId(homeId);
            Oldman oldman2 = oldmanService.selectByOld(oldman1);
            if (oldman2 != null && !oldman2.getOldmanId().equals(oldman.getOldmanId())) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "该身份证号码已被其他老人使用", oldman.getOldIdCard());
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("OldMan.idcard.used", null), oldman.getOldIdCard());
            }
        }
        //计算老人家庭地址的百度经纬度
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getOldAddress())) {
            Map<String, Double> addressMap = BaiduMapUtils.getLngAndLat(oldman.getOldAddress());
            if (addressMap == null || addressMap.isEmpty()) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "请检查老人家庭住址是否正确", null);
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("OldMan.check.address", null), null);
            } else {

                String latitude = addressMap.get("lat").toString();
                String longitude = addressMap.get("lng").toString();
                String addressBdGps = longitude + "," + latitude;
                oldman.setOldAddressBdGps(addressBdGps);
            }
        }
        //根据生日 获取年龄
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getBirthday())) {
            String birthday = "" + oldman.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.parse(birthday);
            int age = 0;
            if (org.apache.commons.lang.StringUtils.isNotBlank(birthday)) {
                age = AgeUtil.getAgeFromBirthTime(birthday) - 1;
            }
            oldman.setOldAge(age);
        }
        //修改
        int n = oldmanService.updateByOldId(oldman);
        if (n <= 0) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "修改失败", 0);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("comment.change.fail", null), 0);
        }
        // 更新redis-老人 缓存
        redisInitRunner.refreshOldman(oldman.getOldmanId());
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "修改成功", n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("comment.change.success", null), n);
    }

    //根据老人id查询老人信息
    @RequestMapping(value = "/selectByOldId", method = RequestMethod.POST)
    public Wrapper selectByOldId(Integer oldmanId) {
        //校验
        if (oldmanId == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人id不能为空", oldmanId);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("oldman.id.null", null), oldmanId);
        }
        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldmanId);
        Oldman oldman1 = oldmanService.selectDescByOld(oldman);
        if (oldman1 == null) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "查询失败", oldmanId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null), oldmanId);
        }
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "查询成功", oldman1);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), oldman1);
    }

    //根据条件查询社区老人信息
    @RequestMapping(value = "/showAll", method = RequestMethod.POST)
    public Wrapper showAll(@RequestBody Map<String, Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        queryMap.put("homeId", homeId);
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Map<String, Object>> mapList = oldmanService.showAll(queryMap);
        PageInfo<Map<String, Object>> info = new PageInfo<>(mapList);
//        if (CollectionUtils.isEmpty(mapList)) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "没有查询到结果", new ArrayList<>());
//        }
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "查询成功", info);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), info);
    }

    //老人状态修改  0-未入院 1-待评估 2-待缴费 3-已入院  4-已出院

    /**
     * 调用该接口的场景：
     * 场景一：点击入院按钮，就调用该接口，给status赋值为1
     * 场景二：当评估完（前端通过判断finalGrade是否为空进行判断是否评估完成）,给status赋值为2
     * 场景三：当老人将套餐选择完后，给status赋值为2
     * 场景四：当老人交完费用后，给status赋值为3
     * 场景五：当老人出院时，给status赋值为4
     */
    @RequestMapping(value = "/changeOldStatus", method = RequestMethod.POST)
    public Wrapper changeOldStatus(Integer oldmanId, Integer status) {
        if (oldmanId == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人id不能为空", oldmanId);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("oldman.id.null", null), oldmanId);
        }
        if (status == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "老人状态值不能为空", status);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("oldman.not.in", null), status);
        }

        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldmanId);
        oldman.setStatus(status);
        oldman.setHomeId(getLoginAuthDto().getGroupId().intValue());
        int n = oldmanService.updateByOldId(oldman);
        if (n <= 0) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "状态改变失败", 0);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null), 0);
        }
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "状态改变成功", n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), n);
    }

    /**
     * 查询老人地图
     *
     * @return the wrapper
     */
    @RequestMapping(value = "/queryOldmanAddress", method = RequestMethod.POST)
    public Wrapper queryOldmanAddress() {

        OldmanAddressQueryDto oldmanAddressQueryDto = new OldmanAddressQueryDto();
        oldmanAddressQueryDto.setGroupId(getLoginAuthDto().getGroupId());
        oldmanAddressQueryDto.setStatus(Constant.YIRUYUAN);
        List<OldmanAddressVo> oldmanAddressVoList = oldmanService.queryOldmanAddress(oldmanAddressQueryDto);

//        return WrapMapper.ok(oldmanAddressVoList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), oldmanAddressVoList);
    }

    /**
     * 查询未绑定手环的老人列表
     *
     * @return the wrapper
     */
    @RequestMapping(value = "/queryOldmanNotBindWatchList", method = RequestMethod.POST)
    public Wrapper queryOldmanNotBindWatchList(@RequestBody OldmanNotBindWatchQueryDto oldmanNotBindWatchQueryDto) {

        oldmanNotBindWatchQueryDto.setGroupId(getLoginAuthDto().getGroupId());
        oldmanNotBindWatchQueryDto.setStatus(Constant.YIRUYUAN);
        PageInfo pageInfo = oldmanService.queryOldmanNotBindWatchList(oldmanNotBindWatchQueryDto);

//        return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), pageInfo);
    }

    //根据条件查询社区老人信息
    @RequestMapping(value = "/showIn", method = RequestMethod.POST)
    public Wrapper showIn(@RequestBody Map<String, Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        queryMap.put("homeId", homeId);
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Map<String, Object>> mapList = oldmanService.showIn(queryMap);
        PageInfo<Map<String, Object>> info = new PageInfo<>(mapList);
//        if (CollectionUtils.isEmpty(mapList)) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "没有查询到结果", new ArrayList<>());
//        }
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "查询成功", info);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), info);
    }

    //根据条件查询社区老人信息
    @RequestMapping(value = "/listPage", method = RequestMethod.POST)
    public Wrapper showIn(@RequestBody OldmanQueryDto oldmanQueryDto) {

        PageInfo pageInfo = oldmanService.listPage(oldmanQueryDto, getLoginAuthDto());

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), pageInfo);
    }


    // 查询某天生日的老人——老人生日
    @RequestMapping(value = "/showAllOldMan", method = RequestMethod.POST)
    public Wrapper showAllOldMan(String date) {
        //校验
        String year = DateUtil.getYear();//获取年份
        String date1 = year + "-" + date;
        Pattern pattern = Pattern.compile("^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])"
                + "|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|"
                + "[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$");
        Matcher matcher1 = pattern.matcher(date1);
        if (!matcher1.matches()) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldManController.showAllOldMan.chaxunshengri", null), null);
        }
        Long groupId = getLoginAuthDto().getGroupId();
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("groupId", groupId);
        queryParam.put("date", date);
        List<OldManVo> list = oldmanService.queryOldManBirthdayByDay(queryParam);
        if (CollectionUtils.isEmpty(list)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldManController.showAllOldMan.meiyou", null), list);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), list);
    }


    //按照月份查询该月老人——返回的数据根据日分组——老人生日
    @RequestMapping(value = "/selectByMonth", method = RequestMethod.POST)
    public Wrapper selectByMonth(String month) {
        if (null == month || "".equals(month)) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldManController.selectByMonth.shentiyuefen", null), null);
        }
        //校验
        String pattern = "^(0+[1-9]|1[0-2])$";
        Integer mon = Integer.parseInt(month);
        if (!Pattern.matches(pattern, month)) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldManController.selectByMonth.shentiyuefen", null), null);
        }
        Long groupId = getLoginAuthDto().getGroupId();
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("groupId", groupId);
        queryParam.put("month", mon);
        List<OldManVo> list = oldmanService.queryOldManBirthdayByMonth(queryParam);
        if (CollectionUtils.isEmpty(list)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldManController.selectByMonth.jasdfjwaE", null), list);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), list);
    }


    /**
     * 添加老人  兼容武昌版  将老人额外信息入库到cn_omc_oldman_supplement表
     *
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/addOldmanWithSupplement", method = RequestMethod.POST)
    public Wrapper addOldmanWithSupplement(@RequestBody OmcOldManWithSupplementDto oldManWithSupplementDto, BindingResult br) throws ParseException {
        Oldman oldman = new Oldman();
        OmcOldManSupplementDto omcOldManSupplementDto = new OmcOldManSupplementDto();
        //转换成老人信息类和老人额外信息类
        BeanUtils.copyProperties(oldManWithSupplementDto, oldman);
        BeanUtils.copyProperties(oldManWithSupplementDto, omcOldManSupplementDto);
        //校验
        if (oldman.getOldIdCard() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.idcard.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getOldName())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("advisoryCancel.oldName.null", null), null);
        }
        if (oldman.getSex() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.sex.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getBirthday())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.chushen.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getOldAddress())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.address.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getmStatus())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.hunyin.notnull", null), null);
        }

        if (PublicUtil.isEmpty(oldManWithSupplementDto.getPeopleType())){
            if (StringUtils.isEmpty(oldman.getEgNamea())) {
                return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.name.notnull", null), null);
            }
            if (StringUtils.isEmpty(oldman.getEgPhonea())) {
                return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.phone.notnull", null), null);
            }
            if (oldman.getRelationshipa() == null) {
                return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.relation.notnull", null), null);
            }
            if (oldman.getEgaAddress() == null) {
                return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.address.notnull", null), null);
            }
        }else {
            OmcUserType omcUserType = userTypeService.selectByKey(oldManWithSupplementDto.getPeopleType());
            if (!omcUserType.getUserTypeCode().equals("1")){
                if (StringUtils.isEmpty(oldman.getEgNamea())) {
                    return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.name.notnull", null), null);
                }
                if (StringUtils.isEmpty(oldman.getEgPhonea())) {
                    return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.phone.notnull", null), null);
                }
                if (oldman.getRelationshipa() == null) {
                    return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.relation.notnull", null), null);
                }
                if (oldman.getEgaAddress() == null) {
                    return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.address.notnull", null), null);
                }
            }
        }



        //验证老人额外信息
        /* 封装需要进行数据校验的字段 */
        List<String> params = new ArrayList<String>();
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getSsCard())) {
            params.add("sscard");
        }
        if (null != omcOldManSupplementDto.getPeopleType()) {
            params.add("peopleType");
        }
        if (null != omcOldManSupplementDto.getIsDisabled()) {
            params.add("isDisabled");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getSpecialCase())) {
            params.add("specialCase");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgAddress())) {
            params.add("egAddress");
        }
        if (omcOldManSupplementDto.getSelfcareStatus() != null) {
            params.add("selfcareStatus");
        }
        if (omcOldManSupplementDto.getReligion() != null) {
            params.add("religion");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDisabledNo())) {
            params.add("disabledNo");
        }
        if (omcOldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (omcOldManSupplementDto.getBDisabledLevel() != null) {
            params.add("bDisabledLevel");
        }
        if (omcOldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOCompany())) {
            params.add("oCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOcContact())) {
            params.add("ocContact");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOcPhone())) {
            params.add("ocPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOCommunity())) {
            params.add("oCommunity");
        }
        if (omcOldManSupplementDto.getIsKeepAshes() != null) {
            params.add("isKeepAshes");
        }
        if (omcOldManSupplementDto.getIsDonate() != null) {
            params.add("isDonate");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDeadTime())) {
            params.add("deadTime");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDeadReason())) {
            params.add("deadReason");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getPsHistory())) {
            params.add("psHistory");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getSpecialDiet())) {
            params.add("specialDiet");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDHistory())) {
            params.add("dHistory");
        }
        if (omcOldManSupplementDto.getEgSex() != null) {
            params.add("egSex");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgName())) {
            params.add("egName");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgPhone())) {
            params.add("egPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgCompany())) {
            params.add("egCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getAnContactB())) {
            params.add("anContactB");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getAnPhoneB())) {
            params.add("anPhoneB");
        }
        if (null != omcOldManSupplementDto.getHeadPic()) {
            params.add("headPic");
        }
        if (null != omcOldManSupplementDto.getRelationShip()) {
            params.add("relationShip");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getIdCardPic())) {
            params.add("idCardPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOutPic())) {
            params.add("outPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOtherPic())) {
            params.add("otherPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getCComphone())) {
            params.add("cComPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getRelativePhone())) {
            params.add("relativePhone");
        }
        String paramValid[] = new String[params.size()];
        for (int i = 0, j = params.size(); i < j; i++) {
            paramValid[i] = params.get(i);
        }
        /* 存放校验错误结果集 */
        Map<String, String> errorMap = ValidateUtil.getErrorMap(br, paramValid);
        if (errorMap != null && errorMap.size() != 0) {
            /* 返回参数校验错误详情 */
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.add.param.error", null), errorMap);
        }

        //计算老人家庭地址的百度经纬度
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getOldAddress())) {
            Map<String, Double> addressMap = BaiduMapUtils.getLngAndLat(oldman.getOldAddress());
            if (addressMap == null || addressMap.isEmpty()) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.check.address", null), null);
            } else {
                String latitude = addressMap.get("lat").toString();
                String longitude = addressMap.get("lng").toString();
                String addressBdGps = longitude + "," + latitude;
                System.out.println("addressBdGps");
                oldman.setOldAddressBdGps(addressBdGps);
            }
        }

        //获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        oldman.setHomeId(homeId);
        //生成用户名(机构Id+随机数+系统时间的形式)
        String username = "nc_" + homeId + "_" +
                (int) (Math.random() * 100) + System.currentTimeMillis();
        oldman.setUserName(username);

        //生日  通过生日计算年龄
        String birthday = "" + oldman.getBirthday();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.parse(birthday);
        int age = 0;
        if (org.apache.commons.lang.StringUtils.isNotBlank(birthday)) {
            age = AgeUtil.getAgeFromBirthTime(birthday) - 1;
        }
        oldman.setOldAge(age);
        oldman.setOldmanNo(DateUtil.getOldmanNo());//生成老人编号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        oldman.setCreateTime(simpleDateFormat.parse(DateUtil.getCurrentDate()));
        oldman.setModifier(loginAuthDto.getUserId());
        //根据身份证号码判断该老人是否已经登记过
        Oldman oldman2 = new Oldman();
        oldman2.setOldIdCard(oldman.getOldIdCard());
        Oldman oldman1 = oldmanService.selectByOld(oldman2);
        if (oldman1 != null) {
            oldman.setOldmanId(oldman1.getOldmanId());
            //有身份证信息有,就代表是转机构的,执行更新操作
            //判断有没有跟原有的机构解绑
            if(null != oldman1.getHomeId() && oldman1.getHomeId() > 0){
                if (oldman1.getStatus()!=Constant.YICHUYUAN&&oldman1.getStatus()!=Constant.WEIRUYUAN){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.is.not.out", null), oldman.getOldIdCard());
                }

            }
            //如果修改了老人身份证，判断该身份证是否和社区的其他老人重复
            if (!StringUtils.isEmpty(oldman.getOldIdCard())) {
                Map<String,Object> queryMap = new HashMap<>();
                queryMap.put("oldManId",oldman1.getOldmanId());
                queryMap.put("oldIdCard",oldman.getOldIdCard());
                boolean result = oldmanService.queryIdCardRepet(queryMap);
                if (result) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.idcard.used", null), oldman.getOldIdCard());
                }
            }

            //如果是再次入院  老人状态为已出院  此时将老人状态设置为待评估
            Oldman oldmanQuery = new Oldman();
            oldmanQuery.setOldmanId(oldman.getOldmanId());

            oldmanQuery = oldmanService.selectByOld(oldmanQuery);

            if(oldmanQuery.getStatus().equals(OldInConstant.YICHUYUAN)){
                oldman.setHomeId(getLoginAuthDto().getGroupId().intValue());
                oldman.setStatus(OldInConstant.DAIPINGGU);
            }else if(oldmanQuery.getStatus().equals(OldInConstant.QUSHI)){
                return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("oldman.status.qushi", null), null);
            }

            //修改
            int n = oldmanService.updateByOldId(oldman);
            if (n <= 0) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.change.fail", null), 0);
            }

            // 更新redis-老人 缓存
            redisInitRunner.refreshOldman(oldman.getOldmanId());

            //修改老人额外信息
            OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
            omcOldManSupplement.setOldManId(oldman.getOldmanId().longValue());
            omcOldManSupplementDto.setOldManId(oldman.getOldmanId().longValue());
            OmcOldManSupplement omcOldManSupplement1 = oldManSupplementService.selectOne(omcOldManSupplement);
            if (null != omcOldManSupplement1) {//有老人额外信息ID就更新,没有就新增老人额外信息
                omcOldManSupplementDto.setId(omcOldManSupplement1.getId());
            }
            int m = saveOldManSupplement(omcOldManSupplementDto);
            //暂存减免比例
            OmcOldManIetypeStash dto = new OmcOldManIetypeStash();
            dto.setOldManId(oldman.getOldmanId().longValue());
            dto.setUserTypeId(omcOldManSupplementDto.getPeopleType());
            omcOldManIetypeStashService.saveIetypeStash(dto, getLoginAuthDto());
            //添加老人账户资金信息
            /*
            * 2020-07-28
            * xcr
            * 二次入院-防止重复添加老人账户
            * */
            OmcOldManAccountFunds fundQuery = new OmcOldManAccountFunds();
            fundQuery.setOldManId(oldman.getOldmanId().longValue());
            fundQuery = accountFundsService.selectOne(fundQuery);
            if(fundQuery != null){
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(loginAuthDto);
                accountFundsService.update(fundQuery);
            }else{
                fundQuery = new OmcOldManAccountFunds();
                fundQuery.setRemainder(BigDecimal.ZERO);
                fundQuery.setActPaidFee(BigDecimal.ZERO);
                fundQuery.setMonetary(BigDecimal.ZERO);
                fundQuery.setRecharge(BigDecimal.ZERO);
                fundQuery.setDeposited(BigDecimal.ZERO);
                fundQuery.setOldManId(oldman.getOldmanId().longValue());
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(loginAuthDto);
                accountFundsService.save(fundQuery);
            }
            /*
             * 更改咨询记录状态
             * */
            if (omcOldManSupplementDto.getAdvisoryId() != null) {
                OmcAdvisory advisory = omcAdvisoryService.selectByKey(omcOldManSupplementDto.getAdvisoryId());
                //咨询转入住
                advisory.setAdvisoryStatus(2);
                int ret = omcAdvisoryService.update(advisory);
            }
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.add.success", null), oldman.getOldmanId());
        }else{//没有身份证信息,老人第一次进入养老院,进行新增操作
            //新增清除老人ID数据
            oldman.setOldmanId(null);
            //设置老人状态为待评估 1
            oldman.setStatus(Constant.DAIPINGGU);
            //添加  返回老人ID
            int n = oldmanService.insertSelective(oldman);
            if (n <= 0) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.add.fail", null), 0);
            }
            //组装参数入库老人额外信息补充表
            omcOldManSupplementDto.setOldManId(oldman.getOldmanId().longValue());
            omcOldManSupplementDto.setGroupId(getLoginAuthDto().getGroupId());
            int m = saveOldManSupplement(omcOldManSupplementDto);
            //暂存减免比例
            OmcOldManIetypeStash dto = new OmcOldManIetypeStash();
            dto.setOldManId(oldman.getOldmanId().longValue());
            dto.setUserTypeId(omcOldManSupplementDto.getPeopleType());
            omcOldManIetypeStashService.saveIetypeStash(dto, getLoginAuthDto());
            //添加老人账户资金信息
            OmcOldManAccountFunds oldManAccountFunds = new OmcOldManAccountFunds();
            oldManAccountFunds.setOldManId(oldman.getOldmanId().longValue());
            oldManAccountFunds.setGroupId(getLoginAuthDto().getGroupId());
            accountFundsService.save(oldManAccountFunds);
            /*
             * 更改咨询记录状态
             * */
            if (omcOldManSupplementDto.getAdvisoryId() != null) {
                OmcAdvisory advisory = omcAdvisoryService.selectByKey(omcOldManSupplementDto.getAdvisoryId());

                if (PublicUtil.isNotEmpty(advisory)){
                    //咨询转入住
                    advisory.setAdvisoryStatus(2);
                    int ret = omcAdvisoryService.update(advisory);
                }

            }

            //创建推送请求对象 老人入院填写基本信息
            SendMessageRequest sendMessageRequest = new SendMessageRequest();
            sendMessageRequest.setMsgCode(OldInConstant.IN_FLOW_RECORD_INFORMATION);
            sendMessageRequest.setGroupId(loginAuthDto.getGroupId());
            opcMessageService.pushWithMsgCode(sendMessageRequest);

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.add.success", null), oldman.getOldmanId());
        }
    }


    /*
    * 乐颐版入院接口
    * */
    @RequestMapping(value = "/addOldmanWithSupplementOfLeyi", method = RequestMethod.POST)
    public Wrapper addOldmanWithSupplementOfLeyi(@RequestBody OmcOldManWithSupplementDto oldManWithSupplementDto, BindingResult br) throws ParseException {
        Oldman oldman = new Oldman();
        OmcOldManSupplementDto omcOldManSupplementDto = new OmcOldManSupplementDto();
        //转换成老人信息类和老人额外信息类
        BeanUtils.copyProperties(oldManWithSupplementDto, oldman);
        BeanUtils.copyProperties(oldManWithSupplementDto, omcOldManSupplementDto);
        //校验
        if (oldman.getOldIdCard() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.idcard.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getOldName())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("advisoryCancel.oldName.null", null), null);
        }
        if (oldman.getSex() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.sex.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getBirthday())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.chushen.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getOldAddress())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.address.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getmStatus())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.hunyin.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getEgNamea())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.name.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getEgaIdCard())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.idcard.notnull", null), null);
        }
        if (StringUtils.isEmpty(oldman.getEgPhonea())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.phone.notnull", null), null);
        }
        if (oldman.getRelationshipa() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.relation.notnull", null), null);
        }
        if (oldman.getEgaAddress() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.urgA.address.notnull", null), null);
        }
        //验证老人额外信息
        /* 封装需要进行数据校验的字段 */
        List<String> params = new ArrayList<String>();
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getSsCard())) {
            params.add("sscard");
        }
        if (null != omcOldManSupplementDto.getPeopleType()) {
            params.add("peopleType");
        }
        if (null != omcOldManSupplementDto.getIsDisabled()) {
            params.add("isDisabled");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getSpecialCase())) {
            params.add("specialCase");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgAddress())) {
            params.add("egAddress");
        }
        if (omcOldManSupplementDto.getSelfcareStatus() != null) {
            params.add("selfcareStatus");
        }
        if (omcOldManSupplementDto.getReligion() != null) {
            params.add("religion");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDisabledNo())) {
            params.add("disabledNo");
        }
        if (omcOldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (omcOldManSupplementDto.getBDisabledLevel() != null) {
            params.add("bDisabledLevel");
        }
        if (omcOldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOCompany())) {
            params.add("oCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOcContact())) {
            params.add("ocContact");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOcPhone())) {
            params.add("ocPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOCommunity())) {
            params.add("oCommunity");
        }
        if (omcOldManSupplementDto.getIsKeepAshes() != null) {
            params.add("isKeepAshes");
        }
        if (omcOldManSupplementDto.getIsDonate() != null) {
            params.add("isDonate");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDeadTime())) {
            params.add("deadTime");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDeadReason())) {
            params.add("deadReason");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getPsHistory())) {
            params.add("psHistory");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getSpecialDiet())) {
            params.add("specialDiet");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getDHistory())) {
            params.add("dHistory");
        }
        if (omcOldManSupplementDto.getEgSex() != null) {
            params.add("egSex");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgName())) {
            params.add("egName");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgPhone())) {
            params.add("egPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getEgCompany())) {
            params.add("egCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getAnContactB())) {
            params.add("anContactB");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getAnPhoneB())) {
            params.add("anPhoneB");
        }
        if (null != omcOldManSupplementDto.getHeadPic()) {
            params.add("headPic");
        }
        if (null != omcOldManSupplementDto.getRelationShip()) {
            params.add("relationShip");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getIdCardPic())) {
            params.add("idCardPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOutPic())) {
            params.add("outPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getOtherPic())) {
            params.add("otherPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getCComphone())) {
            params.add("cComPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(omcOldManSupplementDto.getRelativePhone())) {
            params.add("relativePhone");
        }
        String paramValid[] = new String[params.size()];
        for (int i = 0, j = params.size(); i < j; i++) {
            paramValid[i] = params.get(i);
        }
        /* 存放校验错误结果集 */
        Map<String, String> errorMap = ValidateUtil.getErrorMap(br, paramValid);
        if (errorMap != null && errorMap.size() != 0) {
            /* 返回参数校验错误详情 */
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.add.param.error", null), errorMap);
        }

        //计算老人家庭地址的百度经纬度
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getOldAddress())) {
            Map<String, Double> addressMap = BaiduMapUtils.getLngAndLat(oldman.getOldAddress());
            if (addressMap == null || addressMap.isEmpty()) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.check.address", null), null);
            } else {
                String latitude = addressMap.get("lat").toString();
                String longitude = addressMap.get("lng").toString();
                String addressBdGps = longitude + "," + latitude;
                System.out.println("addressBdGps");
                oldman.setOldAddressBdGps(addressBdGps);
            }
        }

        //获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        oldman.setHomeId(homeId);
        //生成用户名(机构Id+随机数+系统时间的形式)
        String username = "nc_" + homeId + "_" +
                (int) (Math.random() * 100) + System.currentTimeMillis();
        oldman.setUserName(username);

        //生日  通过生日计算年龄
        String birthday = "" + oldman.getBirthday();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.parse(birthday);
        int age = 0;
        if (org.apache.commons.lang.StringUtils.isNotBlank(birthday)) {
            age = AgeUtil.getAgeFromBirthTime(birthday) - 1;
        }
        oldman.setOldAge(age);
        oldman.setOldmanNo(DateUtil.getOldmanNo());//生成老人编号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        oldman.setCreateTime(simpleDateFormat.parse(DateUtil.getCurrentDate()));
        oldman.setModifier(loginAuthDto.getUserId());
        //根据身份证号码判断该老人是否已经登记过
        Oldman oldman2 = new Oldman();
        oldman2.setOldIdCard(oldman.getOldIdCard());
        Oldman oldman1 = oldmanService.selectByOld(oldman2);
        if (oldman1 != null) {
            //有身份证信息有,就代表是转机构的,执行更新操作
            //判断有没有跟原有的机构解绑
            if(null != oldman1.getHomeId() && oldman1.getHomeId() > 0){
                if (oldman1.getStatus()!=Constant.YICHUYUAN&&oldman1.getStatus()!=Constant.WEIRUYUAN){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.is.not.out", null), oldman.getOldIdCard());
                }
            }
            //如果修改了老人身份证，判断该身份证是否和社区的其他老人重复
            if (!StringUtils.isEmpty(oldman.getOldIdCard())) {
                Map<String,Object> queryMap = new HashMap<>();
                queryMap.put("oldManId",oldman1.getOldmanId());
                queryMap.put("oldIdCard",oldman.getOldIdCard());
                boolean result = oldmanService.queryIdCardRepet(queryMap);
                if (result) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.idcard.used", null), oldman.getOldIdCard());
                }
            }
            //修改
            oldman.setStatus(Constant.WEIRUYUAN);
            oldman.setOldmanId(oldman1.getOldmanId());
            int n = oldmanService.updateByOldId(oldman);
            if (n <= 0) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.change.fail", null), 0);
            }

            // 更新redis-老人 缓存
            redisInitRunner.refreshOldman(oldman.getOldmanId());

            //修改老人额外信息
            OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
            omcOldManSupplement.setOldManId(oldman.getOldmanId().longValue());
            omcOldManSupplementDto.setOldManId(oldman.getOldmanId().longValue());
            OmcOldManSupplement omcOldManSupplement1 = oldManSupplementService.selectOne(omcOldManSupplement);
            if (null != omcOldManSupplement1) {//有老人额外信息ID就更新,没有就新增老人额外信息
                omcOldManSupplementDto.setId(omcOldManSupplement1.getId());
            }
            int m = saveOldManSupplement(omcOldManSupplementDto);
            //添加老人账户资金信息
//            OmcOldManAccountFunds oldManAccountFunds = new OmcOldManAccountFunds();
//            oldManAccountFunds.setOldManId(oldman.getOldmanId().longValue());
//            oldManAccountFunds.setGroupId(getLoginAuthDto().getGroupId());
//            accountFundsService.save(oldManAccountFunds);

            /*
             * 2020-07-28
             * xcr
             * 二次入院-防止重复添加老人账户
             * */
            OmcOldManAccountFunds fundQuery = new OmcOldManAccountFunds();
            fundQuery.setOldManId(oldman.getOldmanId().longValue());
            fundQuery = accountFundsService.selectOne(fundQuery);
            if(fundQuery != null){
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(loginAuthDto);
                accountFundsService.update(fundQuery);
            }else{
                fundQuery = new OmcOldManAccountFunds();
                fundQuery.setRemainder(BigDecimal.ZERO);
                fundQuery.setActPaidFee(BigDecimal.ZERO);
                fundQuery.setMonetary(BigDecimal.ZERO);
                fundQuery.setRecharge(BigDecimal.ZERO);
                fundQuery.setDeposited(BigDecimal.ZERO);
                fundQuery.setOldManId(oldman.getOldmanId().longValue());
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(loginAuthDto);
                accountFundsService.save(fundQuery);
            }

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.add.success", null), oldman.getOldmanId());
        }else{//没有身份证信息,老人第一次进入养老院,进行新增操作
            //新增清除老人ID数据
            oldman.setOldmanId(null);
            //设置老人状态为未入院 1
            oldman.setStatus(Constant.WEIRUYUAN);
            //添加  返回老人ID
            int n = oldmanService.insertSelective(oldman);
            if (n <= 0) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.add.fail", null), 0);
            }
            //组装参数入库老人额外信息补充表
            omcOldManSupplementDto.setOldManId(oldman.getOldmanId().longValue());
            omcOldManSupplementDto.setGroupId(getLoginAuthDto().getGroupId());
            int m = saveOldManSupplement(omcOldManSupplementDto);
            //添加老人账户资金信息
            OmcOldManAccountFunds oldManAccountFunds = new OmcOldManAccountFunds();
            oldManAccountFunds.setOldManId(oldman.getOldmanId().longValue());
            oldManAccountFunds.setGroupId(getLoginAuthDto().getGroupId());
            accountFundsService.save(oldManAccountFunds);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.add.success", null), oldman.getOldmanId());
        }
    }

    /**
     * 修改老人
     *
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/updateOldmanWithSupplement", method = RequestMethod.POST)
    public Wrapper updateOldmanWithSupplement(@RequestBody OmcOldManWithSupplementDto oldManWithSupplementDto, BindingResult br) throws ParseException {
        Oldman oldman = new Oldman();
        OmcOldManSupplementDto oldManSupplementDto = new OmcOldManSupplementDto();
        //转换成老人信息类和老人额外信息类
        BeanUtils.copyProperties(oldManWithSupplementDto, oldman);
        BeanUtils.copyProperties(oldManWithSupplementDto, oldManSupplementDto);
        if (oldman.getOldmanId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("MedicationPlan.oldman.id.notnull", null), null);
        }
        //验证老人额外信息
        /* 封装需要进行数据校验的字段 */
        List<String> params = new ArrayList<String>();
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getSsCard())) {
            params.add("sscard");
        }
        if (null != oldManSupplementDto.getPeopleType()) {
            params.add("peopleType");
        }
        if (null != oldManSupplementDto.getIsDisabled()) {
            params.add("isDisabled");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getSpecialCase())) {
            params.add("specialCase");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgAddress())) {
            params.add("egAddress");
        }

        if (oldManSupplementDto.getSelfcareStatus() != null) {
            params.add("selfcareStatus");
        }
        if (oldManSupplementDto.getReligion() != null) {
            params.add("religion");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDisabledNo())) {
            params.add("disabledNo");
        }
        if (oldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (oldManSupplementDto.getBDisabledLevel() != null) {
            params.add("bDisabledLevel");
        }
        if (oldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOCompany())) {
            params.add("oCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOcContact())) {
            params.add("ocContact");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOcPhone())) {
            params.add("ocPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOCommunity())) {
            params.add("oCommunity");
        }
        if (oldManSupplementDto.getIsKeepAshes() != null) {
            params.add("isKeepAshes");
        }
        if (oldManSupplementDto.getIsDonate() != null) {
            params.add("isDonate");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDeadTime())) {
            params.add("deadTime");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDeadReason())) {
            params.add("deadReason");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getPsHistory())) {
            params.add("psHistory");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getSpecialDiet())) {
            params.add("specialDiet");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDHistory())) {
            params.add("dHistory");
        }
        if (oldManSupplementDto.getEgSex() != null) {
            params.add("egSex");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgName())) {
            params.add("egName");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgPhone())) {
            params.add("egPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgCompany())) {
            params.add("egCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getAnContactB())) {
            params.add("anContactB");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getAnPhoneB())) {
            params.add("anPhoneB");
        }
        if (null != oldManSupplementDto.getHeadPic()) {
            params.add("headPic");
        }
        if (null != oldManSupplementDto.getRelationShip()) {
            params.add("relationShip");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getIdCardPic())) {
            params.add("idCardPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOutPic())) {
            params.add("outPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOtherPic())) {
            params.add("otherPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getCComphone())) {
            params.add("cComPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getRelativePhone())) {
            params.add("relativePhone");
        }
        String paramValid[] = new String[params.size()];
        for (int i = 0, j = params.size(); i < j; i++) {
            paramValid[i] = params.get(i);
        }
        /* 存放校验错误结果集 */
        Map<String, String> errorMap = ValidateUtil.getErrorMap(br, paramValid);
        if (errorMap != null && errorMap.size() != 0) {
            /* 返回参数校验错误详情 */
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.add.param.error", null), errorMap);
        }
        //机构id
        Integer homeId = getLoginAuthDto().getGroupId().intValue();
        //如果修改了老人身份证，判断该身份证是否和社区的其他老人重复
        if (!StringUtils.isEmpty(oldman.getOldIdCard())) {
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("oldManId",oldman.getOldmanId());
            queryMap.put("oldIdCard",oldman.getOldIdCard());
            boolean result = oldmanService.queryIdCardRepet(queryMap);
            if (result) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.idcard.used", null), oldman.getOldIdCard());
            }
        }
        //计算老人家庭地址的百度经纬度
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getOldAddress())) {
            Map<String, Double> addressMap = BaiduMapUtils.getLngAndLat(oldman.getOldAddress());
            if (addressMap == null || addressMap.isEmpty()) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.check.address", null), null);
            } else {
                String latitude = addressMap.get("lat").toString();
                String longitude = addressMap.get("lng").toString();
                String addressBdGps = longitude + "," + latitude;
                oldman.setOldAddressBdGps(addressBdGps);
            }
        }
        //根据生日 获取年龄
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getBirthday())) {
            String birthday = "" + oldman.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.parse(birthday);
            int age = 0;
            if (org.apache.commons.lang.StringUtils.isNotBlank(birthday)) {
                age = AgeUtil.getAgeFromBirthTime(birthday) - 1;
            }
            oldman.setOldAge(age);
        }

        //如果是再次入院  老人状态为已出院  此时将老人状态设置为待评估
        Oldman oldmanQuery = new Oldman();
        oldmanQuery.setOldmanId(oldman.getOldmanId());
        oldmanQuery = oldmanService.selectByOld(oldmanQuery);
        if(oldmanQuery.getStatus().equals(OldInConstant.YICHUYUAN)){
            oldman.setHomeId(getLoginAuthDto().getGroupId().intValue());
            oldman.setStatus(OldInConstant.DAIPINGGU);
        }else if(oldmanQuery.getStatus().equals(OldInConstant.QUSHI)){
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("oldman.status.qushi", null), null);
        }

        //修改
        int n = oldmanService.updateByOldId(oldman);
        if (n <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.change.fail", null), 0);
        }

        // 更新redis-老人 缓存
        redisInitRunner.refreshOldman(oldman.getOldmanId());

        //修改老人额外信息
        OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
        omcOldManSupplement.setOldManId(oldman.getOldmanId().longValue());
        oldManSupplementDto.setOldManId(oldman.getOldmanId().longValue());
        OmcOldManSupplement omcOldManSupplement1 = oldManSupplementService.selectOne(omcOldManSupplement);
        if (null != omcOldManSupplement1) {//有老人额外信息ID就更新,没有就新增老人额外信息
            oldManSupplementDto.setId(omcOldManSupplement1.getId());
        }
        int m = saveOldManSupplement(oldManSupplementDto);
        //暂存减免比例
        OmcOldManIetypeStash dto = new OmcOldManIetypeStash();
        dto.setOldManId(oldman.getOldmanId().longValue());
        dto.setUserTypeId(oldManSupplementDto.getPeopleType());
        omcOldManIetypeStashService.saveIetypeStash(dto, getLoginAuthDto());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.change.success", null), n);
    }

    /**
     * 乐颐版修改老人信息
     *
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/updateOldmanWithSupplementOfLeyi", method = RequestMethod.POST)
    public Wrapper updateOldmanWithSupplementOfLeyi(@RequestBody OmcOldManWithSupplementDto oldManWithSupplementDto, BindingResult br) throws ParseException {
        Oldman oldman = new Oldman();
        OmcOldManSupplementDto oldManSupplementDto = new OmcOldManSupplementDto();
        //转换成老人信息类和老人额外信息类
        BeanUtils.copyProperties(oldManWithSupplementDto, oldman);
        BeanUtils.copyProperties(oldManWithSupplementDto, oldManSupplementDto);
        if (oldman.getOldmanId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("MedicationPlan.oldman.id.notnull", null), null);
        }
        //验证老人额外信息
        /* 封装需要进行数据校验的字段 */
        List<String> params = new ArrayList<String>();
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getSsCard())) {
            params.add("sscard");
        }
        if (null != oldManSupplementDto.getPeopleType()) {
            params.add("peopleType");
        }
        if (null != oldManSupplementDto.getIsDisabled()) {
            params.add("isDisabled");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getSpecialCase())) {
            params.add("specialCase");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgAddress())) {
            params.add("egAddress");
        }

        if (oldManSupplementDto.getSelfcareStatus() != null) {
            params.add("selfcareStatus");
        }
        if (oldManSupplementDto.getReligion() != null) {
            params.add("religion");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDisabledNo())) {
            params.add("disabledNo");
        }
        if (oldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (oldManSupplementDto.getBDisabledLevel() != null) {
            params.add("bDisabledLevel");
        }
        if (oldManSupplementDto.getSdDisabledLevel() != null) {
            params.add("sdDisabledLevel");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOCompany())) {
            params.add("oCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOcContact())) {
            params.add("ocContact");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOcPhone())) {
            params.add("ocPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOCommunity())) {
            params.add("oCommunity");
        }
        if (oldManSupplementDto.getIsKeepAshes() != null) {
            params.add("isKeepAshes");
        }
        if (oldManSupplementDto.getIsDonate() != null) {
            params.add("isDonate");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDeadTime())) {
            params.add("deadTime");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDeadReason())) {
            params.add("deadReason");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getPsHistory())) {
            params.add("psHistory");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getSpecialDiet())) {
            params.add("specialDiet");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getDHistory())) {
            params.add("dHistory");
        }
        if (oldManSupplementDto.getEgSex() != null) {
            params.add("egSex");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgName())) {
            params.add("egName");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgPhone())) {
            params.add("egPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getEgCompany())) {
            params.add("egCompany");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getAnContactB())) {
            params.add("anContactB");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getAnPhoneB())) {
            params.add("anPhoneB");
        }
        if (null != oldManSupplementDto.getHeadPic()) {
            params.add("headPic");
        }
        if (null != oldManSupplementDto.getRelationShip()) {
            params.add("relationShip");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getIdCardPic())) {
            params.add("idCardPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOutPic())) {
            params.add("outPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getOtherPic())) {
            params.add("otherPic");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getCComphone())) {
            params.add("cComPhone");
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldManSupplementDto.getRelativePhone())) {
            params.add("relativePhone");
        }
        String paramValid[] = new String[params.size()];
        for (int i = 0, j = params.size(); i < j; i++) {
            paramValid[i] = params.get(i);
        }
        /* 存放校验错误结果集 */
        Map<String, String> errorMap = ValidateUtil.getErrorMap(br, paramValid);
        if (errorMap != null && errorMap.size() != 0) {
            /* 返回参数校验错误详情 */
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.add.param.error", null), errorMap);
        }
        //机构id
        Integer homeId = getLoginAuthDto().getGroupId().intValue();
        //如果修改了老人身份证，判断该身份证是否和社区的其他老人重复
        if (!StringUtils.isEmpty(oldman.getOldIdCard())) {
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("oldManId",oldman.getOldmanId());
            queryMap.put("oldIdCard",oldman.getOldIdCard());
            boolean result = oldmanService.queryIdCardRepet(queryMap);
            if (result) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.idcard.used", null), oldman.getOldIdCard());
            }
        }
        //计算老人家庭地址的百度经纬度
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getOldAddress())) {
            Map<String, Double> addressMap = BaiduMapUtils.getLngAndLat(oldman.getOldAddress());
            if (addressMap == null || addressMap.isEmpty()) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.check.address", null), null);
            } else {
                String latitude = addressMap.get("lat").toString();
                String longitude = addressMap.get("lng").toString();
                String addressBdGps = longitude + "," + latitude;
                oldman.setOldAddressBdGps(addressBdGps);
            }
        }
        //根据生日 获取年龄
        if (org.apache.commons.lang.StringUtils.isNotBlank(oldman.getBirthday())) {
            String birthday = "" + oldman.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.parse(birthday);
            int age = 0;
            if (org.apache.commons.lang.StringUtils.isNotBlank(birthday)) {
                age = AgeUtil.getAgeFromBirthTime(birthday) - 1;
            }
            oldman.setOldAge(age);
        }
        //修改
        int n = oldmanService.updateByOldId(oldman);
        if (n <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.change.fail", null), 0);
        }
        // 更新redis-老人 缓存
        redisInitRunner.refreshOldman(oldman.getOldmanId());

        //修改老人额外信息
        OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
        omcOldManSupplement.setOldManId(oldman.getOldmanId().longValue());
        oldManSupplementDto.setOldManId(oldman.getOldmanId().longValue());
        OmcOldManSupplement omcOldManSupplement1 = oldManSupplementService.selectOne(omcOldManSupplement);
        if (null != omcOldManSupplement1) {//有老人额外信息ID就更新,没有就新增老人额外信息
            oldManSupplementDto.setId(omcOldManSupplement1.getId());
        }
        int m = saveOldManSupplement(oldManSupplementDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.change.success", null), n);
    }


    /**
     * 删除老人档案及其老人额外信息
     *
     * @param oldmanId
     * @return
     */
    @RequestMapping(value = "/delOldmanWithSupplement", method = RequestMethod.POST)
    public Wrapper delOldmanWithSupplement(Integer oldmanId) {
        if (oldmanId == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("MedicationPlan.oldman.id.notnull", null), null);
        }
        int n = oldmanService.deleteByOldId(oldmanId);

        //删除费用记录
        OldmanFee oldmanFee = oldmanFeeService.selectByOldmanId(oldmanId);
        if (oldmanFee != null) {
            oldmanFeeService.deleteByOldmanId(oldmanId);
        }

        //删除出院信息
        oldmanLeaveService.deleteByOid(oldmanId);

        //删除老人入住记录
        oldmanCheckInService.deleteByOldId(oldmanId);

        //解绑老人智能设备
        oldmanCheckInService.delOldDeviceByOid(oldmanId);

        //删除老人护理记录
        oldmanNurseHiService.deleteByOldmanId(oldmanId);

        //删除充值记录
        oldmanRechargeService.deleteByOldmanId(oldmanId);

        //删除老人绑定的个性化套餐纪录
        oldmanCheckInService.delOldItemByOid(oldmanId);

        //删除老人额外信息
        OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
        omcOldManSupplement.setOldManId(oldmanId.longValue());
        oldManSupplementService.delete(omcOldManSupplement);

        if (n <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("id.empty", null), oldmanId);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.delete.sucess", null), n);
    }

    /**
     * 根据老人ID查询单条老人信息及其额外信息
     *
     * @param oldmanId
     * @return
     */
    @RequestMapping(value = "/selectOldManSupByOld", method = RequestMethod.POST)
    public Wrapper selectOldManSupByOld(Integer oldmanId) {
        //校验
        if (oldmanId == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("MedicationPlan.oldman.id.notnull", null), oldmanId);
        }
        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldmanId);
        OldManSupVo oldManSupVo = oldmanService.selectOldManSupByOld(oldman);
        if (null == oldManSupVo) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.query.fail", null), oldmanId);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), oldManSupVo);
    }

    /**
     * 根据条件查询社区老人信息及其额外信息
     *
     * @param queryMap
     * @return
     */
    @RequestMapping(value = "/showOldManSupAll", method = RequestMethod.POST)
    public Wrapper showOldManSupAll(@RequestBody Map<String, Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");
        //解决查询代缴费状态下无法查询出未缴状态的老人
        if(!StringUtils.isEmpty(queryMap.get("status"))){
            //查询待缴费不再查询出所有未缴费状态
            /*if (((Integer)(queryMap.get("status"))).equals(2)) {
                queryMap.put("isPayed", 0);
                queryMap.put("status", null);
            } else*/ if (queryMap.get("status").equals(3)) {

                /**
                 * @author  chisj
                 * @date    2021-07-12 18:24
                 * @desc    查询待评估(1),待缴费(2),已入院(3)记录
                 */
                List<Integer> statList = Lists.newLinkedList();
                statList.add(3);    // 已入院
                statList.add(5);    // 试入住
                statList.add(7);    // 请假中
                statList.add(8);    // 调房调级中
                statList.add(9);    // 出院中
                //statList.add(11);   // 已初评
                /**
                 * @author  chisj
                 * @date    2021-07-22
                 * @desc    12是老人其他缴费单待审批的状态,属于代缴费的状态。
                 */
                // statList.add(12);   // 待审批
                queryMap.put("status", null);
                queryMap.put("statList", statList);
                /*
                * 待缴费状态包括2待缴费，11已初评，12待审批
                * */
            }else if(queryMap.get("status").equals(2)){
                List<Integer> statList = Lists.newLinkedList();
                statList.add(2);
                statList.add(11);
                statList.add(12);
                queryMap.put("status", null);
                queryMap.put("statList", statList);
            }
        }

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        queryMap.put("homeId", homeId);
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<OldManSupVo> list = oldmanService.showOldManSupAll(queryMap);
        PageInfo<OldManSupVo> info = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.query.fail", null), new ArrayList<>());
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), info);
    }


    /**
     * 根据条件查询社区老人信息及其额外信息
     *
     * @param queryMap
     * @return
     */
    @RequestMapping(value = "/showOldManSupIn", method = RequestMethod.POST)
    public Wrapper showOldManSupIn(@RequestBody Map<String, Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        queryMap.put("homeId", homeId);
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<OldManSupVo> list = oldmanService.showOldManSupIn(queryMap);
        PageInfo<OldManSupVo> info = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.query.fail", null), new ArrayList<>());
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), info);
    }

    /**
     * 查询身份证号码是否重复
     *
     * @param queryMap
     * @return
     */
    @RequestMapping(value = "/queryIdCardRepet", method = RequestMethod.POST)
    public Wrapper queryIdCardRepet(@RequestBody Map<String, Object> queryMap) {
        //身份证号码
        String oldIdCard = (String) queryMap.get("oldIdCard");
        if (null == oldIdCard || "".equals(oldIdCard)) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.idcard.notnull", null), null);
        }
        OldManIdentityVo oldManIdentityVo = new OldManIdentityVo();
        boolean result = oldmanService.queryIdCardRepet(queryMap);
        if(result){//如果有重复的身份证,增加返回老人ID
            //根据身份证号码判断该老人是否已经登记过
            Oldman oldman2 = new Oldman();
            oldman2.setOldIdCard(oldIdCard);
            Oldman oldman1 = oldmanService.selectByOld(oldman2);
            if(null != oldman1){
                oldManIdentityVo.setOldManId(oldman1.getOldmanId().longValue());
            }
        }
        oldManIdentityVo.setResult(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), oldManIdentityVo);
    }

    /**
     * 根据身份证号查询老人信息 -- 用于回显老信息
     *
     * @param identity
     * @return
     */
    @RequestMapping(value = "/queryOldManByIdentity", method = RequestMethod.POST)
    public Wrapper queryOldManByIdentity(String identity) {
        if (null == identity || "".equals(identity)) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("OldMan.idcard.notnull", null), null);
        }
        //根据身份证号码判断该老人是否已经登记过
        Oldman oldman2 = new Oldman();
        oldman2.setOldIdCard(identity);
        Oldman oldman1 = oldmanService.selectByOld(oldman2);
        if(null == oldman1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.query.fail", null), null);
        }
        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldman1.getOldmanId());
        OldManSupVo oldManSupVo = oldmanService.selectOldManSupByOld(oldman);
        if (null == oldManSupVo) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.query.fail", null), null);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), oldManSupVo);
    }


    /**
     * 保存或者更新老人额外信息
     *
     * @param: [uacPlanDto]
     * @return: java.lang.Integer
     */
    private Integer saveOldManSupplement(OmcOldManSupplementDto oldManSupplementDto) {
        OmcOldManSupplement oldManSupplement = new OmcOldManSupplement();
        BeanUtils.copyProperties(oldManSupplementDto, oldManSupplement);
        return oldManSupplementService.saveOldManSupplement(oldManSupplement, getLoginAuthDto());
    }

    /**
     * 添加修改入院老人服务类型和护理等级
     */
    @RequestMapping(value = "/updateOldmanInType",method = RequestMethod.POST)
    public Wrapper updateOldmanInType(@RequestBody OmcOldManSupplement omcOldManSupplement) {
        int n = oldmanService.updateByOldType(omcOldManSupplement);
        if(n<=0){
//            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "修改失败", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("operation.failed", null), null);
        } else {
//            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "修改成功", n);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), n);
        }
    }

    /**
     * 查询入院老人服务类型和护理等级
     * @param oldmanId
     * @return
     */
    @RequestMapping(value = "/oldmanInType",method = RequestMethod.POST)
    public Wrapper oldmanInType(@RequestParam Integer oldmanId){
        List<OldManTypeStatusVo> list = oldmanService.selectByOldType(oldmanId);
//        return WrapMapper.ok(list);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), list);
    }

    /**
     * 查询老人异常信息
     * @param oldmanId
     * @return
     */
    @RequestMapping(value = "/queryOldmanException/{oldmanId}", method = RequestMethod.POST)
    public Wrapper queryOldmanException(@PathVariable Long oldmanId) {
        if (null == oldmanId || oldmanId == 0L) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("oldman.id.null", null), null);
        }
        OldmanExceptionVo oldmanExceptionVo = oldmanService.queryOldmanException(oldmanId,getLoginAuthDto());
//        return WrapMapper.ok(oldmanExceptionVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("oldman.id.null", null), oldmanExceptionVo);
    }


    @PostMapping(consumes = "multipart/form-data", value = "/toLead")
    @ApiOperation(httpMethod = "POST", value = "社区版导入老人信息")
    public Wrapper save (HttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile file = multipartRequest.getFile("file");

        Workbook wb = null;

        //校验文件是否为excel格式
        try {
            wb = Workbook.getWorkbook(file.getInputStream());
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.file.error", null));
        }

        // 获得工作薄
        Sheet st = wb.getSheet(0);

        //校验是否填入了数据
        if (st.getColumn(0).length <= 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.null.error", null));
        }
        if (st.getColumn(0).length>300){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.size.long.error", null));
        }

            //对读取的参数循环校验
            for (int i = 1; i < st.getColumn(0).length; i++) {

                //姓名
                if (PublicUtil.isEmpty(st.getCell(0, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldmanName.null", null));
                }
                //年龄
                if (PublicUtil.isNotEmpty(st.getCell(1, i).getContents().trim())){
                    String age = st.getCell(1, i).getContents().trim();
                    Pattern pattern = Pattern.compile("[0-9]*");
                    if (!pattern.matcher(age).matches()){
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.age.error", null));
                    }
                }else {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.age.null", null));
                }
                //性别
                if (PublicUtil.isEmpty(st.getCell(2, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.gender.null", null));
                }
                //身份证号码
                if (PublicUtil.isNotEmpty(st.getCell(3, i).getContents().trim())){
                    //格式
                    String idCard = st.getCell(3, i).getContents().trim();
                    String idCardTemplate = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
                    if (!Pattern.matches(idCardTemplate, idCard)) {
                        String oldName = st.getCell(0, i).getContents().trim();
                        String[]oldNames={oldName};
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCard.error", oldNames));
                    }
                    //此身份证号的老人是否存在
                    Oldman oldman = new Oldman();
                    oldman.setHomeId(getLoginAuthDto().getGroupId().intValue());
                    oldman.setOldIdCard(idCard);
                    Oldman select = oldmanService.selectByOld(oldman);
                    if (PublicUtil.isNotEmpty(select)){
                        String[]idCards={idCard};
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCard.repetition", idCards));
                    }
                }else {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCard.null", null));
                }
                //老人家庭住址
                if (PublicUtil.isEmpty(st.getCell(4, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldManAdress.null", null));
                }
                //紧急联系人
                if (PublicUtil.isEmpty(st.getCell(5, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.egNamea.null", null));
                }
                //紧急联系人电话
                if (PublicUtil.isNotEmpty(st.getCell(6, i).getContents().trim())){
                    String egPhonea = st.getCell(6, i).getContents().trim();
                    String phoneTemplate = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
                    if (!Pattern.matches(phoneTemplate, egPhonea)) {
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.egPhonea.error", null));
                    }
                }else {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.egPhonea.null", null));
                }
                //与老人关系
                if (PublicUtil.isEmpty(st.getCell(7, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.relationshipa.null", null));
                }
                //老人电话
                if (PublicUtil.isNotEmpty(st.getCell(8, i).getContents().trim())){
                    String oldPhone = st.getCell(8, i).getContents().trim();
                    String phoneTemplate = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
                    if (!Pattern.matches(phoneTemplate, oldPhone)) {
                        String oldName = st.getCell(0, i).getContents().trim();
                        String[]oldNames={oldName};
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldPhone.error", oldNames));
                    }
                }else {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.oldPhone.null", null));
                }
                //紧急联系人家庭住址
                if (PublicUtil.isEmpty(st.getCell(9, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.egaAddress.null", null));
                }
                //紧急联系人身份证号
                if (PublicUtil.isNotEmpty(st.getCell(10, i).getContents().trim())){
                    //格式
                    String idCard = st.getCell(10, i).getContents().trim();
                    String idCardTemplate = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
                    if (!Pattern.matches(idCardTemplate, idCard)) {
                        String oldName = st.getCell(0, i).getContents().trim();
                        String[]oldNames={oldName};
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCard.error", oldNames));
                    }
                }else {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.egaIdCard.null", null));
                }
                //老人民族
                if (PublicUtil.isEmpty(st.getCell(11, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldman.nation.null", null));
                }
                //老人婚姻状况
                if (PublicUtil.isEmpty(st.getCell(12, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldman.mStatus.null", null));
                }
                //老人文化情况
                if (PublicUtil.isEmpty(st.getCell(13, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldman.oldEctLel.null", null));
                }
                //老人经济来源
                if (PublicUtil.isEmpty(st.getCell(14, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldman.economicSource.null", null));
                }
                //老人月收入
                if (PublicUtil.isEmpty(st.getCell(15, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldman.oldMonIncome.null", null));
                }

            }

            int result=0;

        //写入以及存储参数
        for (int i = 1; i < st.getColumn(0).length; i++) {

            //取出数据
            String oldName = st.getCell(0, i).getContents().trim();
            String age = st.getCell(1, i).getContents().trim();
            String gender = st.getCell(2, i).getContents().trim();
            String idCard = st.getCell(3, i).getContents().trim();
            String oldAddress = st.getCell(4, i).getContents().trim();
            String egNamea = st.getCell(5, i).getContents().trim();
            String egPhonea = st.getCell(6, i).getContents().trim();
            String relationshipa = st.getCell(7, i).getContents().trim();
            String oldPhone = st.getCell(8, i).getContents().trim();
            String egaAddress = st.getCell(9, i).getContents().trim();
            String egaIdCard = st.getCell(10, i).getContents().trim();
            String nation = st.getCell(11, i).getContents().trim();
            String mStatus = st.getCell(12, i).getContents().trim();
            String oldEctLel = st.getCell(13 ,i).getContents().trim();
            String economicSource = st.getCell(14 ,i).getContents().trim();
            String oldMonIncome = st.getCell(15 ,i).getContents().trim();

            //写入数据
            Oldman oldman = new Oldman();
            oldman.setOldName(oldName);
            oldman.setOldAge(Integer.valueOf(age));
            oldman.setSex(OldManStatusUtils.toSexByString(gender));
            oldman.setOldIdCard(idCard);
            oldman.setOldAddress(oldAddress);
            oldman.setEgNamea(egNamea);
            oldman.setEgPhonea(egPhonea);
            //老人与紧急联系人关系
            oldman.setRelationshipa(OldManStatusUtils.toRelationshipaByString(relationshipa));
            oldman.setOldPhone(oldPhone);
            oldman.setEgaAddress(egaAddress);
            oldman.setStatus(OldInConstant.DAIPINGGU);
            oldman.setUserName(getLoginAuthDto().getUserName());
            oldman.setHomeId(getLoginAuthDto().getGroupId().intValue());
            oldman.setCreateId(getLoginAuthDto().getUserId().intValue());
            oldman.setCreateTime(new Date());
            oldman.setOldmanNo(DateUtil.getOldmanNo());
            oldman.setEgaIdCard(egaIdCard);
            //老人婚姻状况
            oldman.setmStatus(OldManStatusUtils.toMStatus(mStatus));
            //老人文化程度
            oldman.setOldEctLel(OldManStatusUtils.toOldEctLelByString(oldEctLel));
            //老人经济来源
            oldman.setEconomicSource(OldManStatusUtils.toEconomicSourceByString(economicSource));
            oldman.setOldMonIncome(oldMonIncome);
            oldman.setBirthday(OldManStatusUtils.toBirthdatByIdCard(idCard));
            oldman.setNation(NationsUtils.toIntByNations(nation));

            //计算百度地图经纬度
            Map<String, Double> addressMap = BaiduMapUtils.getLngAndLat(oldman.getOldAddress());
            if (addressMap == null || addressMap.isEmpty()) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("OldMan.check.address", null), null);
            } else {
                String latitude = addressMap.get("lat").toString();
                String longitude = addressMap.get("lng").toString();
                String addressBdGps = longitude + "," + latitude;
                System.out.println("addressBdGps");
                oldman.setOldAddressBdGps(addressBdGps);
            }

            //新增老人信息
            result += oldmanService.insertSelective(oldman);

            //新增老人补充表数据
            OmcOldManSupplement supplement = new OmcOldManSupplement();
            supplement.setOldManId(oldman.getOldmanId().longValue());
            supplement.setGroupId(getLoginAuthDto().getGroupId());
            supplement.setCreator(getLoginAuthDto().getUserName());
            supplement.setCreatorId(getLoginAuthDto().getUserId());
            oldManSupplementService.save(supplement);


            /*
             * 2020-07-28
             * xcr
             * 二次入院-防止重复添加老人账户
             * */
            OmcOldManAccountFunds fundQuery = new OmcOldManAccountFunds();
            fundQuery.setOldManId(oldman.getOldmanId().longValue());
            fundQuery = accountFundsService.selectOne(fundQuery);
            if(fundQuery != null){
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(getLoginAuthDto());
                accountFundsService.update(fundQuery);
            }else{
                fundQuery = new OmcOldManAccountFunds();
                fundQuery.setRemainder(BigDecimal.ZERO);
                fundQuery.setActPaidFee(BigDecimal.ZERO);
                fundQuery.setMonetary(BigDecimal.ZERO);
                fundQuery.setRecharge(BigDecimal.ZERO);
                fundQuery.setDeposited(BigDecimal.ZERO);
                fundQuery.setOldManId(oldman.getOldmanId().longValue());
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(getLoginAuthDto());
                accountFundsService.save(fundQuery);
            }
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /*
    * 机构老人列表导入
    * */
    @PostMapping(consumes = "multipart/form-data", value = "/toLeadOldMan")
    public Wrapper saveOldman (HttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile file = multipartRequest.getFile("file");

        Workbook wb = null;

        //校验文件是否为excel格式
        try {
            wb = Workbook.getWorkbook(file.getInputStream());
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.file.error", null));
        }

        // 获得工作薄
        Sheet st = wb.getSheet(0);

        //校验是否填入了数据
        if (st.getColumn(0).length <= 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.null.error", null));
        }
        if (st.getColumn(0).length>300){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.size.long.error", null));
        }

        //对读取的参数循环校验
        for (int i = 1; i < st.getColumn(0).length; i++) {

            //姓名
            if (PublicUtil.isEmpty(st.getCell(0, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldmanName.null", null));
            }
            //身份证号码
            if (PublicUtil.isNotEmpty(st.getCell(1, i).getContents().trim())){
                //格式
                String idCard = st.getCell(1, i).getContents().trim();
                String idCardTemplate = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
                if (!Pattern.matches(idCardTemplate, idCard)) {
                    String oldName = st.getCell(0, i).getContents().trim();
                    String[]oldNames={oldName};
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCard.error", oldNames));
                }
                //此身份证号的老人是否存在
                Oldman oldman = new Oldman();
                oldman.setHomeId(getLoginAuthDto().getGroupId().intValue());
                oldman.setOldIdCard(idCard);
                Oldman select = oldmanService.selectByOld(oldman);
                if (PublicUtil.isNotEmpty(select)){
                    String[]idCards={idCard};
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCard.repetition", idCards));
                }
            }else {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCard.null", null));
            }
            //性别
            if (PublicUtil.isEmpty(st.getCell(2, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.gender.null", null));
            }
            //社保账号
            if(PublicUtil.isEmpty(st.getCell(3, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.shebaoka.notnull", null));
            }
            //出生日期
            if(PublicUtil.isEmpty(st.getCell(4, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.chushen.notnull", null));
            }
            //是否残疾
            if(PublicUtil.isEmpty(st.getCell(5, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.canji.notnull", null));
            }
            //残疾证编号
            if(st.getCell(5,i).getContents().trim().equals("是")){
                if(PublicUtil.isEmpty(st.getCell(6, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("Examine.shifou.code.notnull", null));
                }
            }
            //老人婚姻状况
            if (PublicUtil.isEmpty(st.getCell(7, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldman.mStatus.null", null));
            }
            //老人的人员类别
            if(PublicUtil.isEmpty(st.getCell(8, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("user.type.name.is.not.null", null));
            }
            //老人家庭住址
            if (PublicUtil.isEmpty(st.getCell(9, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldManAdress.null", null));
            }
            //老人经济来源
            if (PublicUtil.isEmpty(st.getCell(10, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.oldman.economicSource.null", null));
            }
            //根据人员类别判断必填选项
            if(st.getCell(8, i).getContents().trim().equals("政府供养特困对象")){
                //原籍所在街道社区
                if (PublicUtil.isEmpty(st.getCell(11, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.ocommunity.null", null));
                }
                //现籍所在街道社区
                if (PublicUtil.isEmpty(st.getCell(12, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.ccommunity.null", null));
                }
                //亲属联系电话
                if (PublicUtil.isEmpty(st.getCell(13, i).getContents().trim())){

                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.qinshu.phone.notnull", null));
                }else {
                    Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$");
                    Matcher m = p.matcher(st.getCell(13, i).getContents().trim());
                    if(!m.matches()){
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.qinshu.phone.pattem.error", null));
                    }
                }
                //现籍所在社区电话
                if (PublicUtil.isEmpty(st.getCell(14, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.ccomphone.null", null));
                }else {
                    Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$");
                    Matcher m = p.matcher(st.getCell(14, i).getContents().trim());
                    if(!m.matches()){
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.qinshu.phone.pattem.error", null));
                    }
                }
                //骨灰
                if (PublicUtil.isEmpty(st.getCell(15, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.baoliuguhui.notnull", null));
                }
                //遗体
                if (PublicUtil.isEmpty(st.getCell(16, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.juanzeng.notnull", null));
                }
            }

            if(!(st.getCell(8, i).getContents().trim().equals("政府供养特困对象"))){
                //申请人姓名
                if (PublicUtil.isEmpty(st.getCell(17, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.shenqing.null", null));
                }
                //申请人性别
                if (PublicUtil.isEmpty(st.getCell(18, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.shenqing.sex.null", null));
                }
                //申请人身份证
                if (PublicUtil.isNotEmpty(st.getCell(19, i).getContents().trim())){
                    //格式
                    String idCard = st.getCell(19, i).getContents().trim();
                    String idCardTemplate = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
                    if (!Pattern.matches(idCardTemplate, idCard)) {
                        String applyName = st.getCell(17, i).getContents().trim();
                        String[]applyNames={applyName};
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.uploading.idCardS.error", applyNames));
                    }
                }else {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.shenqing.IDCard.null", null));
                }
                //与老人关系
                if (PublicUtil.isEmpty(st.getCell(20, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.xiuyang.null", null));
                }
                //申请人地址
                if (PublicUtil.isEmpty(st.getCell(21, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.shenqing.address.null", null));
                }
                //申请人电话
                if (PublicUtil.isEmpty(st.getCell(22, i).getContents().trim())){
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("excel.down.shenqing.phone.null", null));
                }else {
                    Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-9])|(147))\\d{8}$");
                    Matcher m = p.matcher(st.getCell(22, i).getContents().trim());
                    if(!m.matches()){
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.shenqing.phone.pattem.error", null));
                    }
                }
            }

            //特殊说明
            /*if (PublicUtil.isEmpty(st.getCell(17, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.ywebrfsd.notnull", null));
            }*/

            //同意休养人员独立外出活动
            if (PublicUtil.isEmpty(st.getCell(23, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.isOut.notnull", null));
            }

            //是否将休养人员限制在床上或者房内
            if (PublicUtil.isEmpty(st.getCell(24, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.isLimit.notnull", null));
            }

            //休养人紧急情况下是否允许院方诊治
            if (PublicUtil.isEmpty(st.getCell(25, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.isTreat.notnull", null));
            }

            //夜间是否吵闹干扰他人
            if (PublicUtil.isEmpty(st.getCell(26, i).getContents().trim())){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("OldMan.isNoisy.notnull", null));
            }

        }

        int result=0;

        //写入以及存储参数
        for (int i = 1; i < st.getColumn(0).length; i++) {

            //取出数据
            String oldName = st.getCell(0, i).getContents().trim();
            String idCard = st.getCell(1, i).getContents().trim();
            String gender = st.getCell(2, i).getContents().trim();
            String ssCard = st.getCell(3, i).getContents().trim();
            String birthday = st.getCell(4, i).getContents().trim();
            String isDisabled = st.getCell(5, i).getContents().trim();
            String disabledNo = st.getCell(6, i).getContents().trim();
            String mStatus = st.getCell(7, i).getContents().trim();
            String serviceType = st.getCell(8, i).getContents().trim();
            String oldAddress = st.getCell(9, i).getContents().trim();
            String economicSource = st.getCell(10 ,i).getContents().trim();
            String ocommunity = st.getCell(11 ,i).getContents().trim();
            String ccommunity = st.getCell(12 ,i).getContents().trim();
            String relativePhone = st.getCell(13 ,i).getContents().trim();
            String ccomphone = st.getCell(14 ,i).getContents().trim();
            String isKeepAshes = st.getCell(15 ,i).getContents().trim();
            String isDonate = st.getCell(16 ,i).getContents().trim();
            //String specialCase = st.getCell(17 ,i).getContents().trim();
            String eg_name = st.getCell(17 ,i).getContents().trim();
            String eg_sex = st.getCell(18 ,i).getContents().trim();
            String eg_id_card = st.getCell(19 ,i).getContents().trim();
            String relation_ship = st.getCell(20 ,i).getContents().trim();
            String eg_address = st.getCell(21 ,i).getContents().trim();
            String eg_phone = st.getCell(22 ,i).getContents().trim();
            String isOut = st.getCell(23 ,i).getContents().trim();
            String isLimit = st.getCell(24 ,i).getContents().trim();
            String isTreat = st.getCell(25 ,i).getContents().trim();
            String isNoisy = st.getCell(26 ,i).getContents().trim();


            //写入数据
            Oldman oldman = new Oldman();
            OmcOldManSupplement supplement = new OmcOldManSupplement();
            oldman.setOldName(oldName);
            oldman.setOldIdCard(idCard);
            //生日  通过生日计算年龄
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try{
                sdf.parse(OldManStatusUtils.toBirthdatByIdCard(idCard));
                int age = 0;
                if (org.apache.commons.lang.StringUtils.isNotBlank(birthday)) {
                    age = AgeUtil.getAgeFromBirthTime(birthday) - 1;
                }
                oldman.setOldAge(age);
            }catch (Exception e){

            }
            oldman.setSex(OldManStatusUtils.toSexByString(gender));
            oldman.setBirthday(OldManStatusUtils.toBirthdatByIdCard(idCard));
            oldman.setOldAddress(oldAddress);
            oldman.setmStatus(OldManStatusUtils.toMStatus(mStatus));
            oldman.setStatus(OldInConstant.DAIPINGGU);
            oldman.setUserName(getLoginAuthDto().getUserName());
            oldman.setHomeId(getLoginAuthDto().getGroupId().intValue());
            oldman.setCreateId(getLoginAuthDto().getUserId().intValue());
            oldman.setCreateTime(new Date());
            oldman.setOldmanNo(DateUtil.getOldmanNo());
            if(!serviceType.equals("政府供养特困对象")){
                oldman.setEgNamea(eg_name);
                oldman.setEgaIdCard(eg_id_card);
                oldman.setEgaAddress(eg_address);
                oldman.setEgPhonea(eg_phone);
                oldman.setRelationshipa(OldManStatusUtils.toRelationshipaByString(relation_ship));
            }
            supplement.setSsCard(ssCard);
            supplement.setIsDisabled(OldManStatusUtils.toIsDisabled(isDisabled));
            supplement.setDisabledNo(disabledNo);
            supplement.setPeopleType(OldManStatusUtils.toPeopleType(serviceType));
            oldman.setEconomicSource(OldManStatusUtils.toEconomicSourceByString(economicSource));
            supplement.setOCommunity(ocommunity);
            supplement.setCCommunity(ccommunity);
            supplement.setRelativePhone(relativePhone);
            supplement.setCComphone(ccomphone);
            if(PublicUtil.isNotEmpty(isKeepAshes)){
                supplement.setIsKeepAshes(OldManStatusUtils.toKeepByString(isKeepAshes));
            }
            if(PublicUtil.isNotEmpty(isDonate)){
                supplement.setIsDonate(OldManStatusUtils.toDonateByString(isDonate));
            }
            supplement.setSpecialCase(OldManStatusUtils.toOutByString(isOut)+"-"+
                    OldManStatusUtils.toLimitByString(isLimit)+"-"+
                    OldManStatusUtils.toTreatByString(isTreat)+"-"+
                    OldManStatusUtils.toNoisyByString(isNoisy));
            if(!serviceType.equals("政府供养特困对象")){
                supplement.setEgName(eg_name);
                supplement.setEgSex(OldManStatusUtils.toSexByString(eg_sex));
                supplement.setEgIdCard(eg_id_card);
                supplement.setEgAddress(eg_address);
                supplement.setEgPhone(eg_phone);
                supplement.setRelationShip(OldManStatusUtils.toRelationshipaByString(relation_ship));
            }



            //新增老人信息
            result += oldmanService.insertSelective(oldman);

            //新增老人补充表数据
            supplement.setOldManId(oldman.getOldmanId().longValue());
            supplement.setLastOperator(getLoginAuthDto().getUserName());
            supplement.setGroupId(getLoginAuthDto().getGroupId());
            supplement.setCreator(getLoginAuthDto().getUserName());
            supplement.setCreatorId(getLoginAuthDto().getUserId());
            oldManSupplementService.save(supplement);


            /*
             * 2020-07-28
             * xcr
             * 二次入院-防止重复添加老人账户
             * */
            OmcOldManAccountFunds fundQuery = new OmcOldManAccountFunds();
            fundQuery.setOldManId(oldman.getOldmanId().longValue());
            fundQuery = accountFundsService.selectOne(fundQuery);
            if(fundQuery != null){
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(getLoginAuthDto());
                accountFundsService.update(fundQuery);
            }else{
                fundQuery = new OmcOldManAccountFunds();
                fundQuery.setRemainder(BigDecimal.ZERO);
                fundQuery.setActPaidFee(BigDecimal.ZERO);
                fundQuery.setMonetary(BigDecimal.ZERO);
                fundQuery.setRecharge(BigDecimal.ZERO);
                fundQuery.setDeposited(BigDecimal.ZERO);
                fundQuery.setOldManId(oldman.getOldmanId().longValue());
                fundQuery.setGroupId(getLoginAuthDto().getGroupId());
                fundQuery.setUpdateInfo(getLoginAuthDto());
                accountFundsService.save(fundQuery);
            }
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /*
    * 大数据平台注册用户占比查询
    * */
    @RequestMapping(value = "/index",method = RequestMethod.POST)
    public Wrapper selectByGroup(){
        Long groupId = getLoginAuthDto().getGroupId();
        Map<String,Object> result = new HashMap<>();
        List<PercentVo> registerVos = oldmanService.selectByGroup(groupId);
        List<PercentVo> healthVos = oldmanService.selectByHealth(groupId);
        NurseHomeVo nurseHomeVo = groupService.selectByNursingHome(groupId);
        List<PercentVo> serviceOrderVo = oldmanService.selectByService(groupId);
        VolunteerVo volunteerVo = omcServiceService.selectByVolunteer(groupId);
        result.put("registerVos",registerVos);
        result.put("healthVos",healthVos);
        result.put("nurseHomeVo",nurseHomeVo);
        result.put("serviceOrderVo",serviceOrderVo);
        result.put("volunteerVo",volunteerVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /*
     * 大数据平台健康占比亚健康展示
     * */
   /* @RequestMapping(value = "/selectByHealth",method = RequestMethod.POST)
    public Wrapper selectByHealth(){
        Long groupId = getLoginAuthDto().getGroupId();
        List<PercentVo> percentVos = oldmanService.selectByHealth(groupId);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),healthVo);
    }

    /*
     * 大数据平台居家养老服务展示
     * */
    /*@RequestMapping(value = "/selectByService",method = RequestMethod.POST)
    public Wrapper selectByService(){
        Long groupId = getLoginAuthDto().getGroupId();
        ServiceOrderVo serviceOrderVo = oldmanService.selectByService(groupId);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),serviceOrderVo);
    }*/

    /*
     * 大数据平台居家养老服务展示-签约老人数据
     * */
    @PostMapping("/selectOldmanByNurseHome")
    public Wrapper selectOldmanByNurseHome(@RequestBody OlderNumVo olderNumVo){
        olderNumVo.setGroupId(getLoginAuthDto().getGroupId());
        List<OlderNumVo> olderNumVos = oldmanService.selectOldmanByNurseHome(olderNumVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),olderNumVos);
    }

    /*
     * 大数据平台居家养老服务展示-居家服务数据
     * */
    @PostMapping("/selectServiceByNurseHome")
    public Wrapper selectServiceByNurseHome(){
        Long groupId = getLoginAuthDto().getGroupId();
        List<ServiceOrderVo> serviceOrderVos = oldmanService.selectServiceByNurseHome(groupId);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),serviceOrderVos);
    }

    /*
     * 大数据平台居家养老服务展示-居家服务数据
     * */
    @PostMapping("/selectOrderByNurseHome")
    public Wrapper selectOrderByNurseHome(@RequestBody ServiceOrderVO serviceOrderVO){
        Long groupId = getLoginAuthDto().getGroupId();
        serviceOrderVO.setGroupId(groupId);
        List<ServiceOrderVO> serviceOrderVOS = oldmanService.selectOrderByNurseHome(serviceOrderVO);
        List<ServiceOrderVO> serviceOrder = new ArrayList<>();
        List<Integer> statusList = new ArrayList<>();
        ServiceInforVo serviceInforVo = new ServiceInforVo();
        Integer compeleted = 0,
                uncompeleted = 0,
                compeleting = 0;
        /*if(serviceOrderVO.getOrderStatus() != null){
            //已完成
            if(serviceOrderVO.getOrderStatus() == 1){
                statusList.add(4);
            }
            //未完成
            if(serviceOrderVO.getOrderStatus() == 2){
                statusList.add(1);
                statusList.add(2);
                statusList.add(3);
                statusList.add(5);
                statusList.add(6);
                statusList.add(7);
                statusList.add(8);

            }
            //进行中
            if(serviceOrderVO.getOrderStatus() == 3){
                statusList.add(2);
                statusList.add(3);
            }

        }*/
        for (ServiceOrderVO serviceOrderVo:serviceOrderVOS) {
            if(serviceOrderVo.getOrderStatus() != null && serviceOrderVo.getOrderStatus() == 4){
                compeleted++;
            }
            if(serviceOrderVo.getOrderStatus() != null && serviceOrderVo.getOrderStatus() != 4){
                uncompeleted++;
            }
            if(serviceOrderVo.getOrderStatus() != null && (serviceOrderVo.getOrderStatus() == 2 || serviceOrderVo.getOrderStatus() == 3)){
                compeleting++;
            }
        }

        serviceInforVo.setServices(serviceOrderVOS.size());
        serviceInforVo.setCompeleted(compeleted);
        serviceInforVo.setUncompeleted(uncompeleted);
        serviceInforVo.setCompeleting(compeleting);
        serviceInforVo.setServiceOrderVOS(serviceOrderVOS);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),serviceInforVo);
    }

    /*
    *大健康数据添加
    * */
    @PostMapping("/updateHealth")
    public Wrapper updateHealth(@RequestBody OldmanHealthVo oldmanHealthVo){
        OmcOldManSupplement omcOldManSupplement = new OmcOldManSupplement();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("oldmanId", oldmanHealthVo.getOldmanId());
        List<OldManSupVo> oldManSupVos = oldmanService.showOldManSupAll(queryMap);
        if(oldManSupVos.size() == 0){
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource
                    .getMessage("oldman.id.null.inHome", null), null);
        }
        BeanUtils.copyProperties(oldmanHealthVo,omcOldManSupplement);
        omcOldManSupplement.setOldManId(oldmanHealthVo.getOldmanId().longValue());
        Integer result = oldManSupplementService.updateHealth(omcOldManSupplement);
        if(result > 0){
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),result);
        }
        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("operation.failed", null),result);
    }

    /*
    * 集团化查询老人信息
    * */
    @PostMapping("/selectAllOldman")
    public Wrapper selectAllOldman(@RequestBody OldManSupVo oldManSupVo){
        oldManSupVo.setHomeId(getLoginAuthDto().getGroupId().intValue());
        PageHelper.startPage(oldManSupVo.getPageNum(), oldManSupVo.getPageSize());
        List<OldManSupVo> oldManSupVos = oldmanService.selectAllOldman(oldManSupVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),new PageInfo<>(oldManSupVos));
    }

    /*
    * 老人咨询查询
    * */
    @PostMapping("/selectAdvisory")
    public Wrapper selectAdvisory(@RequestBody OldmanAdvisoryVo oldmanAdvisoryVo){
        oldmanAdvisoryVo.setGroupId(getLoginAuthDto().getGroupId());
        PageHelper.startPage(oldmanAdvisoryVo.getPageNum(), oldmanAdvisoryVo.getPageSize());
        List<OldmanAdvisoryVo> oldmanAdvisoryVos = oldmanService.selectAdvisory(oldmanAdvisoryVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),new PageInfo<>(oldmanAdvisoryVos));
    }

    /**
      * 查询首页老人分类占比
     * @return Wrapper
     * @author HD
     * @date 2021/11/26 13:54
     */
    @PostMapping("/selectOldmanIndex")
    public Wrapper selectOldmanIndex(){
        OldmanIndexVo oldmanIndexVo = oldmanService.selectOldmanIndex(getLoginAuthDto().getGroupId());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null),oldmanIndexVo);
    }

}
